<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top: 20px;">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <el-steps
        :space="200"
        :active="activeIxd - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          tabPosition="left"
          v-model="activeIxd"
          :before-leave="beforelae"
          @tab-click="tabcked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <div class="block">
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props="options"
                  @change="handleChange"
                ></el-cascader>
              </div>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyData"
              :key="index"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="ie"
                  v-for="(ie, idx) in item.attr_vals"
                  :key="idx"
                >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2"
            >商品属性
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uplaUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="hds"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
              <!-- 富文本 -->
              <quill-editor v-model="addForm.goods_introduce" ></quill-editor>
              <el-button type="primary" class="btn" @click="addsp">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
  title="图片预览"
  :visible.sync="previewVisible"
  width="30%"
  >
    <img :src="previewpath" alt="">
</el-dialog>
  </div>
</template>

<script>
import _ from "lodash"
export default {
  name: "",
  // 组件注册
  components: {},
  // 父组件传参
  props: {},
  // 变量声明
  data() {
    return {
        previewVisible:false,
      activeIxd: "0",
      addForm: {
        //添加商品的表单
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [], //图片数据
        goods_introduce:'',
        attrs:[]
      },
      addrules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      cateList: [], // 商品分类数据
      options: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      manyData: [], //动态参数数据
      onlyData: [], // 静态属性数据
      uplaUrl: "https://www.liulongbin.top:8888/api/private/v1/upload",
      hds: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewpath:''
    };
  },
  // Vue实例创建完成以后执行 数据可用
  created() {
    this.getCateList();
  },
  // Vue模板挂载完毕以后执行  DOM节点加载完毕了（可以获取节点了）
  mounted() {},
  // keepalive 缓存进入执行
  activited() {},
  // vue组件更新完毕以后执行
  update() {},
  // 定义事件
  methods: {
    async getCateList() {
      let res = await this.$axios.get("categories");
      console.log(res);
      let { meta, data } = res.data;
      if (meta.status == 200) {
        this.cateList = data;
      }
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    beforelae(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择分类");
        return false;
      }
    },
    async tabcked() {
      // console.log(this.activeIxd)
      // 动态参数面板
      if (this.activeIxd === "1") {
        // console.log("动态参数面板")
        let res = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        console.log(res);
        let { meta, data } = res.data;
        if (meta.status == 200) {
          data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          });
          this.manyData = data;
          console.log(this.manyData);
        }
      } else if (this.activeIxd === "2") {
        let res = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        let { meta, data } = res.data;
        if (meta.status === 200) {
          console.log(data);
          this.onlyData = data;
        }
      }
    },
    // 图片预览
    handlePreview(file) {
      console.log(file);
      this.previewpath = file.response.data.url
      this.previewVisible = true
     
    },
    //删除图片
    handleRemove(file) {
      const picImg = file.response.data.tmp_path;
      const idx = this.addForm.pics.findIndex((x) => x.pic === picImg);
      this.addForm.pics.splice(idx, 1);
    },
    // 图片上传成功事件
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path };
      this.addForm.pics.push(picInfo);
    },
    addsp(){
        console.log(this.addForm)
        this.$refs.addForm.validate(async valid =>{
            if(!valid){
                return this.$message.error("请先填写必要的表单")
            }
            const from = _.cloneDeep(this.addForm)
            from.goods_cat=from.goods_cat.join(",")
            this.manyData.forEach(item =>{
                const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(" ")}
                this.addForm.attrs.push(newInfo)
            })
            this.onlyData.forEach(item =>{
                const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals}
                this.addForm.attrs.push(newInfo)
            })
            from.attrs = this.addForm.attrs
            console.log(from)
              let {data:res} = await this.$axios.post("goods",from);
              console.log(res);
            if(res.meta.status !==201){
              return this.$message.error("添加失败")
            }
            this.$message.success("添加成功")
            this.$router.push("/goods")
        })
    }
  },
  // 过滤器
  filter: {},
  // 计算属性
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
  // 监听属性
  watch: {},
};
</script>

<style scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
img{ 
    width: 100%;
}
.ql-editor{
    height:300px;
    
}
.btn{
    margin-top:10px;
}
</style>
